package main

import (
	"sync/atomic"
	"fmt"
	"sync"
	"errors"
	"strings"
)

type UserRouter struct {
	sync.Mutex
	rmap map[string]*LinkList
}
var UserRouterI *UserRouter
var subA int32 = 0

func GetAuthKey(key string) string{
	atomic.AddInt32(&subA,1)
	return fmt.Sprintf("%s:%d",key,subA)
}

func InitUserRouter(){
	UserRouterI = &UserRouter{}
	UserRouterI.rmap = make(map[string]*LinkList)
}

func (r *UserRouter)PutToRouter(userid string) string{
	token := GetAuthKey(userid)
	r.Lock()
	defer r.Unlock()
	if _,ok := r.rmap[userid]; !ok{
		r.rmap[userid] = NewLinkList()
	}
	r.rmap[userid] = r.rmap[userid].Append(token)
	return token
}

func (r *UserRouter)GetFromRouter(userid string) (*LinkList,error){
	r.Lock()
	defer r.Unlock()
	if tokens,ok := r.rmap[userid];!ok{
		return nil,errors.New("the user not online or not exist")
	}else{
		return tokens,nil
	}
}

func (r *UserRouter)RemoveFromRouter(token string){
	useridAndSeq := strings.Split(token,":")
	userid := useridAndSeq[0]
	r.Lock()
	defer  r.Unlock()
	if tokens,ok := r.rmap[userid];!ok{
		return
	}else{
		if tokens.size == 1{
			delete(r.rmap,userid)
			return
		}
		if err := tokens.Remove(token);err != nil{
			fmt.Println(err)
		}
	}
}

func (r *UserRouter)GetOnlineUser() []string{
	users := []string{}
	for userid,_ := range r.rmap{
		users = append(users,userid)
	}
	return users
}



